package com.lzxr.test.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

public class ImageVerificationCode {
    private int weight = 100;
    private int height = 40;
    private String text;
    private Random r = new Random();
    private String[] fontNames = new String[]{"Georgia"};
    private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";

    public ImageVerificationCode() {
    }

    private Color randomColor() {
        int r = this.r.nextInt(225);
        int g = this.r.nextInt(225);
        int b = this.r.nextInt(225);
        return new Color(r, g, b);
    }

    private Font randomFont() {
        int index = this.r.nextInt(this.fontNames.length);
        String fontName = this.fontNames[index];
        int style = this.r.nextInt(4);
        int size = this.r.nextInt(10) + 24;
        return new Font(fontName, style, size);
    }

    private char randomChar() {
        int index = this.r.nextInt(this.codes.length());
        return this.codes.charAt(index);
    }

    private void drawLine(BufferedImage image) {
        int num = this.r.nextInt(10);
        Graphics2D g = (Graphics2D)image.getGraphics();

        for(int i = 0; i < num; ++i) {
            int x1 = this.r.nextInt(this.weight);
            int y1 = this.r.nextInt(this.height);
            int x2 = this.r.nextInt(this.weight);
            int y2 = this.r.nextInt(this.height);
            g.setColor(this.randomColor());
            g.drawLine(x1, y1, x2, y2);
        }

    }

    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(this.weight, this.height, 1);
        Graphics2D g = (Graphics2D)image.getGraphics();
        g.setColor(new Color(255, 255, this.r.nextInt(245) + 10));
        g.fillRect(0, 0, this.weight, this.height);
        return image;
    }

    public BufferedImage getImage() {
        BufferedImage image = this.createImage();
        Graphics2D g = (Graphics2D)image.getGraphics();
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < 4; ++i) {
            String s = this.randomChar() + "";
            sb.append(s);
            float x = (float)i * 1.0F * (float)this.weight / 4.0F;
            g.setFont(this.randomFont());
            g.setColor(this.randomColor());
            g.drawString(s, x, (float)(this.height - 5));
        }

        this.text = sb.toString();
        this.drawLine(image);
        return image;
    }

    public String getText() {
        return this.text;
    }

    public void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}
